import { createStore } from "vuex";
import createPersistedState from "vuex-persistedstate";
import { routes } from "@/router";

function filterRoutes(routes, jurisdiction) {
  const result = [];
  routes.forEach((item) => {
    const tmp = { ...item };
    if (jurisdiction.includes(tmp.name)) {
      if (tmp.children) {
        tmp.children = filterRoutes(tmp.children, jurisdiction);
      }
      result.push(tmp);
    }
  });
  return result;
}

// const name = sessionStorage.getItem("username");
const store = createStore({
  state() {
    return {
      //用户姓名
      name: "",

      //左侧菜单栏是否收起
      isshow: false,

      //权限
      jurisdiction: [],
      //身份 1 - 管理员  2 - 超级管理员
      role: "",
    };
  },
  mutations: {
    getname(state, data) {
      state.name = data.data.adminname;
      state.role = data.data.role;
      state.jurisdiction = data.data.checkedkeys;
      // sessionStorage.setItem("username", username);
    },
    changeshow(state) {
      state.isshow = !state.isshow;
    },
  },
  getters: {
    getjurisdictionroute(state) {
      const arr = routes.filter((item) => !item.hidden);
      if (state.role === 2) {
        return arr;
      } else {
        return filterRoutes(arr, state.jurisdiction);
      }
    },
  },

  //插件  同步更新
  plugins: [createPersistedState({})],
});

export default store;
